<?php

namespace app\api\controller;

use app\common\model\Help;
use think\Controller;
use think\Request;
use think\Db;
use think\facade\Validate;
use app\api\model\SystemOrganization;

class Organization extends Controller
{
    /**
     * 获取组织列表
     */
    public function index(Request $request)
    {
        try {
            $param = $request->param();
            if ($param) {
                $params = $param['params'] ?? [];
            }

            // 构建查询条件
            $where = [];
            if (!empty($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }

            if (!empty($params['system_user_id'])) {
                $where[] = ['system_user_id', '=', $params['system_user_id']];
            }else{
                $help = new Help();
                $system_user = $help->system_user_find();
                if($system_user){
                    if($system_user['role']!='superAdmin'){
                        $where[] = ['system_user_id', '=', $system_user['id']];
                    }
                }
            }

            // 先查询所有组织
            $allMenus = Db::name('system_organization')
                ->order('sort ASC, id ASC')->where($where)
                ->select();
            foreach ($allMenus as $k =>&$v){
                $v['create_at'] = date('Y-m-d H:i:s',$v['create_time']);
                $v['truename'] = Db::table("system_user")->where(['id'=>$v['system_user_id']])->value('truename');
            }

            // 如果有标题过滤
            if (!empty($params['title'])) {
                // 1. 找到所有匹配标题的组织ID
                $matchedIds = [];
                foreach ($allMenus as $menu) {
                    if (stripos($menu['title'], $params['title']) !== false) {
                        $matchedIds[] = $menu['id'];
                    }
                }

                if (empty($matchedIds)) {
                    return []; // 没有匹配的组织
                }


                // 2. 获取所有相关的组织ID（匹配的组织 + 所有父级 + 所有子级）
                $relatedIds = $this->getAllRelatedMenuIds($allMenus, $matchedIds);

                // 3. 过滤出相关的组织
                $filteredMenus = [];
                foreach ($allMenus as $menu) {
                    if (in_array($menu['id'], $relatedIds)) {
                        $filteredMenus[] = $menu;
                    }
                }

                // 4. 构建树形结构
                $tree = $this->buildTree($filteredMenus);
            } else {
                // 没有过滤条件，直接构建完整树
                $tree = $this->buildTree($allMenus);
            }


            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $tree
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取组织列表失败：' . $e->getMessage()
            ]);
        }
    }


    /**
     * 获取组织详情
     */
    public function read()
    {
        $id = input("id") ?? '';
        try {
            $menu = Db::name('system_organization')->where('id', $id)->find();

            if (!$menu) {
                return json([
                    'code' => 400,
                    'message' => '组织不存在'
                ]);
            }

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $menu
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取组织详情失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 新增组织
     */
    public function save(Request $request)
    {
        try {
            $data = $request->param();

            // 验证数据
            $validate = $this->getValidate();
            if (!$validate->check($data)) {
                return json([
                    'code' => 400,
                    'message' => $validate->getError()
                ]);
            }

            // 处理数据
            $insertData = [
                'title' => $data['title'],
                'pid' => $data['pid'] ?? 0,
                'remark' => $data['remark'] ?? '',
                'curator' => $data['curator'] ?? '',
                'sort' => $data['sort'] ?? 0,
                'status' => $data['status'],
                'create_time' => time(),
                'update_time' => time()
            ];

            $id = Db::name('system_organization')->insertGetId($insertData);

            $help = new Help();
            $help->system_log($data, '新建组织');

            return json([
                'code' => 200,
                'message' => '新增成功',
                'data' => ['id' => $id]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '新增组织失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新组织
     */
    public function update(Request $request)
    {
        try {
            $data = $request->param();
            $id = $data['id'];

            // 检查组织是否存在
            $menu = Db::name('system_organization')->where('id', $id)->find();
            if (!$menu) {
                return json([
                    'code' => 400,
                    'message' => '组织不存在'
                ]);
            }

            // 验证数据
            $validate = $this->getValidate();
            if (!$validate->check($data)) {
                return json([
                    'code' => 400,
                    'message' => $validate->getError()
                ]);
            }

            // 处理数据
            $updateData = [
                'title' => $data['title'],
                'pid' => $data['pid'] ?? 0,
                'remark' => $data['remark'] ?? '',
                'curator' => $data['curator'] ?? '',
                'sort' => $data['sort'] ?? 0,
                'status' => $data['status'],
                'update_time' => time()
            ];

            Db::name('system_organization')->where('id', $id)->update($updateData);

            $help = new Help();
            $help->system_log($data, '修改组织');

            return json([
                'code' => 200,
                'message' => '更新成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '更新组织失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 删除组织
     */
    public function delete()
    {
        $id = input("id") ?? '';
        try {
            // 检查组织是否存在
            $menu = Db::name('system_organization')->where('id', $id)->find();
            if (!$menu) {
                return json([
                    'code' => 400,
                    'message' => '组织不存在'
                ]);
            }

            if($menu['pid']==0){
                return json([
                    'code' => 400,
                    'message' => '顶级节点不能删除'
                ]);
            }

            // 检查是否有子组织
            $childCount = Db::name('system_organization')->where('pid', $id)->count();
            if ($childCount > 0) {
                return json([
                    'code' => 400,
                    'message' => '请先删除子组织'
                ]);
            }

            Db::name('system_organization')->where('id', $id)->delete();


            $help = new Help();
            $help->system_log($id, '删除组织');

            return json([
                'code' => 200,
                'message' => '删除成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '删除组织失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 更新组织状态
     */
    public function update_status(Request $request)
    {
        $id = input("id") ?? '';
        try {
            $status = $request->param('status');

            if (!in_array($status, [1, 2])) {
                return json([
                    'code' => 400,
                    'message' => '状态值不正确'
                ]);
            }

            // 检查组织是否存在
            $menu = Db::name('system_organization')->where('id', $id)->find();
            if (!$menu) {
                return json([
                    'code' => 400,
                    'message' => '组织不存在'
                ]);
            }

            Db::name('system_organization')->where('id', $id)->update([
                'status' => $status,
                'update_time' => time()
            ]);

            return json([
                'code' => 200,
                'message' => '状态更新成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '更新状态失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取组织树（用于下拉选择）
     */
    public function tree()
    {
        try {
            $where = "";
            $help = new Help();
            $system_user = $help->system_user_find();
            if($system_user){
                if($system_user['role']!='superAdmin'){
                    $where = "system_user_id=".$system_user['id'];
                }
            }

            $menus = Db::name('system_organization')->where($where)
                ->where('status', 1)
                ->field('id, title, pid')
                ->order('sort ASC, id ASC')
                ->select();

            $tree = $this->buildTree($menus);

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $tree
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取组织树失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取所有相关的组织ID（包括匹配的组织、所有父级组织、所有子级组织）
     */
    private function getAllRelatedMenuIds($allMenus, $matchedIds)
    {
        $relatedIds = $matchedIds;

        // 获取所有父级组织ID
        $parentIds = $this->getAllParentIds($allMenus, $matchedIds);
        $relatedIds = array_merge($relatedIds, $parentIds);

        // 获取所有子级组织ID
        $childIds = $this->getAllChildIds($allMenus, $matchedIds);
        $relatedIds = array_merge($relatedIds, $childIds);

        return array_unique($relatedIds);
    }

    /**
     * 递归获取所有父级组织ID
     */
    private function getAllParentIds($allMenus, $ids)
    {
        $parentIds = [];

        foreach ($allMenus as $menu) {
            if (in_array($menu['id'], $ids)) {
                // 如果当前组织有父级，且父级不是0
                if ($menu['pid'] > 0) {
                    $parentIds[] = $menu['pid'];
                    // 递归获取父级的父级
                    $grandParentIds = $this->getAllParentIds($allMenus, [$menu['pid']]);
                    $parentIds = array_merge($parentIds, $grandParentIds);
                }
            }
        }

        return array_unique($parentIds);
    }

    /**
     * 递归获取所有子级组织ID
     */
    private function getAllChildIds($allMenus, $ids)
    {
        $childIds = [];

        foreach ($allMenus as $menu) {
            if (in_array($menu['pid'], $ids)) {
                $childIds[] = $menu['id'];
                // 递归获取子级的子级
                $grandChildIds = $this->getAllChildIds($allMenus, [$menu['id']]);
                $childIds = array_merge($childIds, $grandChildIds);
            }
        }

        return array_unique($childIds);
    }

    /**
     * 构建树形结构（你原来的方法）
     */
    private function buildTree($menus, $pid = 0)
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['pid'] == $pid) {
                $children = $this->buildTree($menus, $menu['id']);
                if ($children) {
                    $menu['children'] = $children;
                }
                $tree[] = $menu;
            }
        }
        return $tree;
    }

    /**
     * 获取扁平组织列表（用于树形选择器）
     */
    public function flatList(Request $request)
    {
        $param = $request->param();

        $where = "";
        if (!empty($param['system_user_id'])) {
            $where = "system_user_id=".$param['system_user_id'];
        }else{
            $help = new Help();
            $system_user = $help->system_user_find();
            if($system_user){
                if($system_user['role']!='superAdmin'){
                    $where = "system_user_id=".$system_user['id'];
                }
            }
        }

        try {
            $menus = Db::name('system_organization')
                ->where('status', 1)->where($where)
                ->field('id, title, pid')
                ->order('sort ASC, id ASC')
                ->select();

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $menus
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取组织列表失败：' . $e->getMessage()
            ]);
        }
    }


    /**
     * 获取验证器
     */
    private function getValidate()
    {
        $rule = [
            'title' => 'require|max:20',
            'pid' => 'require|number',
            'sort' => 'number',
            'status' => 'require|in:1,2'
        ];

        $message = [
            'title.require' => '组织名称不能为空',
            'title.max' => '组织名称长度不能超过20',
            'pid.require' => '父级组织不能为空',
            'pid.number' => '父级组织格式不正确',
            'sort.number' => '排序必须是数字',
            'status.require' => '显示状态不能为空',
            'status.in' => '显示状态值不正确'
        ];

        return Validate::make($rule, $message);
    }


    //获取组织Id 查询所属租户 创建的角色列表
    public function roleList(){
        $id = input("id")??'';
        $system_user_id = Db::table('system_organization')->where(['id'=>$id])->value('system_user_id');
        $list = [];
        if($system_user_id){
            $list = Db::table("system_role")->where(["system_user_id"=>$system_user_id])->select();
        }
        return json([
            'code' => 200,
            'message' => 'success',
            'data' => $list
        ]);
    }

    //全部角色
    public function roleAllList(){
        $list = Db::table("system_role")->select();
        return json([
            'code' => 200,
            'message' => 'success',
            'data' => $list
        ]);
    }

    /**
     * 获取所有下级组织ID（包括自身）
     */
    public function getAllChildrenIds($id)
    {
        $ids = [$id];
        $children = Db::table("system_organization")->where('pid', $id)->column('id');

        foreach ($children as $childId) {
            $ids = array_merge($ids, $this->getAllChildrenIds($childId));
        }

        return $ids;
    }


    //获取组织Id 查询所属租户 创建的角色列表
    public function memberList(){
        $id = input("id")??'';
        $where = "";
        $organizationId_ids = $this->getAllChildrenIds($id);
        if($organizationId_ids){
            $str = implode(',',$organizationId_ids);
            $where = "organization_id in ($str)";
        }

        $list = Db::table("system_user")->field("id,truename")->where("identity='成员'")->where($where)->select();
        return json([
            'code' => 200,
            'message' => 'success',
            'data' => $list
        ]);
    }




}